package com.qf.myrbac.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.myrbac.sys.entity.SysDept;
import com.qf.myrbac.sys.entity.SysRole;
import com.qf.myrbac.sys.service.SysDeptService;
import com.qf.myrbac.sys.service.SysRoleService;
import com.qf.myrbac.utils.PageVo;
import com.qf.myrbac.utils.ResultMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author 徐英海
 * @since 2022-10-27
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysDeptService deptService;

    @RequiresPermissions("sys:role:list")//权限注解
    @GetMapping("/list")
    public ResultMap list(@RequestParam Map<String, Object> params) {
        PageVo<SysRole> pageVo = roleService.queryByPage(params);
        QueryWrapper<SysDept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.isNotNull("name");
        Map<Long, String> map = new HashMap<>();
        deptService.list(deptQueryWrapper).forEach(dept -> map.put(dept.getDeptId(), dept.getName()));
        pageVo.getList().forEach(role -> role.setDeptName(map.get(role.getDeptId())));
        return ResultMap.ok().put("page", pageVo);
    }

    @RequiresPermissions("sys:role:save")//权限注解
    @PostMapping("/save")
    public ResultMap save(@RequestBody SysRole sysRole) {
        roleService.saveRoleAndAll(sysRole);
        return ResultMap.ok();
    }

    @GetMapping("/info/{roleId}")
    public ResultMap info(@PathVariable("roleId") Long roleId) {
        SysRole role = roleService.getRoleById(roleId);
        return ResultMap.ok().put("role", role);
    }

    @RequiresPermissions("sys:role:update")//权限注解
    @PostMapping("/update")
    public ResultMap update(@RequestBody SysRole role) {
        roleService.updateAndAll(role);
        return ResultMap.ok("更新成功");
    }

    @RequiresPermissions("sys:role:delete")//权限注解
    @PostMapping("/delete")
    public ResultMap delete(@RequestBody Long[] ids) {
        roleService.removeAndAll(ids);
        return ResultMap.ok("删除成功");
    }
}
